<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use DB;

class OrderBackExpressInfo extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'book:order-back-express-info';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '获取回寄订单物流信息';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->info("开始获取...");

        $orders = DB::table('orders')->where('status',3)->where('back_status',1)->get();

        if(!empty($orders))
        {
            foreach ($orders as $v)
            {
                if(!empty($v->back_express_code) && !empty($v->back_express_no))
                {
                    $now = time();
                    $result = getOrderTracesByJson($v->back_express_code,$v->back_express_no,$v->back_order_no);
                    $result = json_decode($result,true);

                    $traces = !empty($result['Traces'])?json_encode($result['Traces']):'';
                    $state = isset($result['State'])?$result['State']:0;


                    $express_info = DB::table('order_express_infos')->where('order_id',$v->id)->where('type',2)->where('express_no',$v->back_express_no)->first();
                    if(empty($express_info))
                    {
                        DB::table('order_express_infos')->insert([
                            'order_id' => $v->id,
                            'express_no' => $v->back_express_no,
                            'state' => $state,
                            'traces' => $traces,
                            'type' => 2
                        ]);
                    }
                    else
                    {
                        DB::table('order_express_infos')->where('id',$express_info->id)->update([
                            'state' => $state,
                            'traces' => $traces
                        ]);
                    }

                    //已签收 更改订单状态
                    if($state == 3 || $state == 2 || $state == 1)
                    {
                        DB::table('orders')->where('id',$v->id)->update([
                            'back_status' => 2
                        ]);
                    }
                }
            }
        }

        $this->info("成功获取...");
    }
}
